package net.gazhi.delonix.core.entity;

import java.util.HashMap;

/**
 * 扩展 HashMap，增加一些基本类型的计算方法<br>
 * 可作为报表统计时的计算使用
 * 
 * @author Jeffrey Lin
 *
 */
public class PrimitiveTypeMap extends HashMap<Object, Object> {
	private static final long serialVersionUID = 1L;

	public PrimitiveTypeMap() {
		super();
	}

	public PrimitiveTypeMap(int length) {
		super(length);
	}

	public void add(Object key, int val) {
		put(key, intValue(key) + val);
	}

	public void add(Object key, long val) {
		put(key, longValue(key) + val);
	}

	public void add(Object key, float val) {
		put(key, floatValue(key) + val);
	}

	public void add(Object key, double val) {
		put(key, doubleValue(key) + val);
	}

	public int intValue(Object key) {
		Object val = get(key);
		if (val == null) {
			return 0;
		}
		if (val instanceof Number) {
			return ((Number) val).intValue();
		}
		if (val instanceof Boolean) {
			return (Boolean) val ? 1 : 0;
		}
		return Integer.parseInt(val.toString());
	}

	public long longValue(Object key) {
		Object val = get(key);
		if (val == null) {
			return 0;
		}
		if (val instanceof Number) {
			return ((Number) val).longValue();
		}
		if (val instanceof Boolean) {
			return (Boolean) val ? 1 : 0;
		}
		return Long.parseLong(val.toString());
	}

	public double floatValue(Object key) {
		Object val = get(key);
		if (val == null) {
			return 0.0;
		}
		if (val instanceof Number) {
			return ((Number) val).floatValue();
		}
		if (val instanceof Boolean) {
			return (Boolean) val ? 1 : 0;
		}
		return Float.parseFloat(val.toString());
	}

	public double doubleValue(Object key) {
		Object val = get(key);
		if (val == null) {
			return 0.0;
		}
		if (val instanceof Number) {
			return ((Number) val).doubleValue();
		}
		if (val instanceof Boolean) {
			return (Boolean) val ? 1L : 0L;
		}
		return Double.parseDouble(val.toString());
	}

	public boolean booleanValue(Object key) {
		Object val = get(key);
		if (val == null) {
			return false;
		}
		if (val instanceof Number) {
			return ((Number) val).intValue() != 0;
		}
		if (val instanceof Boolean) {
			return (Boolean) val;
		}
		return Boolean.parseBoolean(val.toString());
	}

	public String stringValue(Object key) {
		Object val = get(key);
		if (val == null) {
			return null;
		}
		if (val instanceof Object) {
			return (String) val;
		}
		return val.toString();
	}

}
